# -*-coding:utf-8 -*-
# author: leemon
# datetime: 2020/11/17 下午5:56
import json
from requests.exceptions import RequestException
import requests


class WxWorkAlerter:
    def __init__(self, content='', mentioned_list=[], mentioned_mobile_list=[], webhook=''):
        self.content = content
        self.mentioned_list = mentioned_list
        self.mentioned_mobile_list = mentioned_mobile_list
        self.webhook = webhook

    def alert(self):
        if not self.webhook or not self.content:
            return "Required message:(webhook or content) invalid"

        body = self.content

        return self.send_data(body)

    def send_data(self, content):
        if len(content) > 2048:
            content = content[:2045] + "..."

        send_url = self.webhook
        headers = {'content-type': 'application/json'}

        payload = {
            'msgtype': "text",
            "text": {
                "content": content,  # 避免中文字符发送失败
                "mentioned_list": self.mentioned_list,
                "mentioned_mobile_list": self.mentioned_mobile_list,
            },
        }
        data = json.dumps(payload).encode('utf-8')
        try:
            response = requests.post(send_url, data=data, headers=headers)
            response.raise_for_status()
        except RequestException as e:
            raise Exception("send message has error: %s" % e)

        return response.text
